﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;

namespace PropertyManagement.Core {
    public static class SettingHelper {
        private const string DBSetfileName = "dbsetting.ini";
        private const string LogFileName = "log.txt";
        public static string RootFolder { get; set; }

        private static string GetFilePath() {
            if (string.IsNullOrEmpty(RootFolder)) {
                return DBSetfileName;
            }
            return RootFolder + Path.AltDirectorySeparatorChar + DBSetfileName;
        }

        public static void WriteDBConnectionSetting(string conStr) {
            using (var fw = new StreamWriter(GetFilePath(), false, Encoding.GetEncoding("GB2312"))) {
                fw.WriteLine(conStr);
            }
        }

        public static string ReadDBConnectionSetting( ) {
            try {
                using (
                    var fw = new StreamReader(GetFilePath( ),
                                              Encoding.GetEncoding("GB2312"))) {
                    return fw.ReadLine( );
                }
            } catch {
                return null;
            }
        }

        public static string GetDBConnectString( ) {
            return ReadDBConnectionSetting() ?? "";// ConfigurationManager.ConnectionStrings["DefaultStudentCourseSystemDB"].ConnectionString;
        }

        public static void Log(string content) {
            using (var fw = new StreamWriter(RootFolder + Path.AltDirectorySeparatorChar + LogFileName, true, Encoding.GetEncoding("GB2312"))) {
                fw.WriteLine(content);
            }
        }

        public static bool HasDBSetFile {
            get { return File.Exists(GetFilePath( )); }
        }
    }
}
